import { useUserStore } from '@/stores/user'
import Mock from 'mockjs'
import { ref } from 'vue'

const checkCode = ref('')

Mock.mock('/login/register', 'post', (config) => {
    const user = useUserStore()
    const req = JSON.parse(config.body)

    const data = {
        code: '200',
        message: '注册失败',
        data: {
            flag: false
        }
    }
    if (user.isTelinList(req.tel) && req.tel) {
        data.message = '注册成功'
        user.adduser(req)
        data.data.flag = true
    }

    return data
})

Mock.mock('/login/getCode', 'post', (config) => {

    checkCode.value = String(Math.random()).slice(2, 8)

    const data = {
        code: '200',
        message: '验证码获取成功',
        data: {
            code: checkCode.value
        }
    }

    return data
})

Mock.mock('/login/login', 'post', (config) => {
    const req = JSON.parse(config.body)

    const user = useUserStore()
    const data = {
        code: '200',
        message: '登录失败',
        data: {
            flag: false
        }
    }
    if (!user.isTelinList(req.tel)) {
        if (req.method) {
            if (checkCode.value == req.code) {
                data.message = '登录成功'
                user.setUserInfo(req.tel)
                checkCode.value = ''
                data.data.flag = true
            } else {
                data.message = '验证码错误'
            }
        } else {
            const flag = user.loginForPassword({
                tel: req.tel,
                password: req.password
            })
            if (flag) {
                data.message = '登录成功'
                data.data.flag = true
            } else {
                data.message = '密码错误'
            }
        }
    } else {
        data.message = '该手机号未注册'
    }
    return data
})

Mock.mock('/login/checkCode', 'post', (config) => {
    const req = JSON.parse(config.body)
    const data = {
        code: '200',
        message: '验证码错误',
        data: {
            flag: false
        },
    }
    if (checkCode.value == req.code) {
        data.message = '下一步'
        data.data.flag = true
    }
    return data
})

Mock.mock('/login/setNewPassword', 'post', (config) => {
    const req = JSON.parse(config.body)
    const user = useUserStore()

    user.setNewPassword(req)

    return {
        code: '200',
        message: '设置密码成功',
        data: {
            flag: true
        },
    }
})